/**
 * 剑指 Offer 18. 删除链表的节点
 * https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
 */
const { createListNode, displayListNode } = require('../../libs/public');

/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
function deleteNode(head, val) {
  if (head.val === val) {
    const result = head.next;
    head.next = null;
    return result;
  }
  let pre = head;
  let { next } = head;
  while (next) {
    if (next.val === val) {
      break;
    }
    pre = next;
    next = next.next;
  }
  pre.next = next.next;
  next.next = null;
  return head;
}

console.log(displayListNode(deleteNode(createListNode([4, 5, 1, 9]), 5)) === '[4,1,9]');
console.log(displayListNode(deleteNode(createListNode([4, 5, 1, 9]), 1)) === '[4,5,9]');
console.log(displayListNode(deleteNode(createListNode([4, 5, 1, 9]), 4)) === '[5,1,9]');
console.log(displayListNode(deleteNode(createListNode([2]), 2)) === '[]');
